package com.kingtone.rongji.pay.alipay;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.alipay.android.app.sdk.AliPay;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

public class AliPayActivity extends Activity
{
	private static final int RQF_PAY = 1;
	private static final String TAG = AliPayActivity.class.getName();
	private String subject = null;///商品主题
	private String body = null;//商品描述
	private double price= 0.00;//商品价格
	private String resultMsg =  "支付失败，请稍候再试";
	private String resultStatus = "-111";
	
 protected void onCreate(Bundle paramBundle)
  {
    super.onCreate(paramBundle);
    //setContentView(R.layout.activity_pay);
    //获取上个页面传过来的商品信息
    Intent intent = getIntent();
    this.subject = intent.getStringExtra("subject");
    this.body = intent.getStringExtra("body");
    this.price = intent.getDoubleExtra("price", 0.00);
    //调用支付接口
    if(!TextUtils.isEmpty(subject) && !TextUtils.isEmpty(body) && price > 0)
    {
    	pay();
    }
  }

   Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Result result = new Result((String) msg.obj);

			switch (msg.what) {
			case RQF_PAY:
			{
				  result.parseResult();  
				  resultMsg  = result.memo;
				  resultStatus = result.resultStatus;
				  Intent intent = new Intent();
	              intent.putExtra("resultMsg",resultMsg);
	              intent.putExtra("resultStatus",resultStatus);
	              setResult(RESULT_OK, intent);
	              finish();
				  //Toast.makeText(PayActivity.this, result.getResult(), Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};
 
 @SuppressWarnings("deprecation")
 private void pay()
 {
	 try {
			String info = getNewOrderInfo(subject, body, price);
			String sign = Rsa.sign(info, Keys.PRIVATE);
			sign = URLEncoder.encode(sign);
			info += "&sign=\"" + sign + "\"&" + getSignType();
			Log.i("ExternalPartner", "start pay");
			// start the pay.
			Log.i(TAG, "info = " + info);

			final String orderInfo = info;
			new Thread() {
				public void run() {
					AliPay alipay = new AliPay(AliPayActivity.this, mHandler);
					//设置为沙箱模式，不设置默认为线上环境
					//alipay.setSandBox(true);

					String result = alipay.pay(orderInfo);
					Log.i(TAG, "result = " + result);
					Message msg = new Message();
					msg.what = RQF_PAY;
					msg.obj = result;
					mHandler.sendMessage(msg);
				}
			}.start();

		} catch (Exception ex) {
			ex.printStackTrace();
			 Intent intent = new Intent();
             intent.putExtra("resultMsg","请安装支付宝手机客户端");
             intent.putExtra("resultStatus",-1);
			 setResult(RESULT_OK, intent);
             finish();
		}
 }
 
 private String getSignType() 
 {
		return "sign_type=\"RSA\"";
 }
 
 @SuppressWarnings("deprecation")
private String getNewOrderInfo(String subject, String body, double price) {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(getOutTradeNo());
		sb.append("\"&subject=\"");
		sb.append(subject);
		sb.append("\"&body=\"");
		sb.append(body);
		sb.append("\"&total_fee=\"");
		sb.append("" + price);
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder.encode("http://www.rongji365.com/Purchase/PaymentNotify"));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}
 
 private String getOutTradeNo() 
 {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		Date date = new Date();
		String key = format.format(date);

		java.util.Random r = new java.util.Random();
		key += r.nextInt();
		key = key.substring(0, 15);
		Log.d(TAG, "outTradeNo: " + key);
		return key;
	}

  protected void onResume()
  {
    super.onResume();
  }
}